<?php

namespace app\api\controller\goods;
use app\common\controller\BaseController;
use app\common\service\order\TblmOrderService;
use app\common\service\product\ShopProductService;
use app\common\service\system\SettingService;
use app\common\validate\goods\GoodsValidate;
use DateTime;
use hg\apidoc\annotation as Apidoc;
use thirdsdk\Http;

/**
 * @Apidoc\Title("商品管理")
 * @Apidoc\Group("product")
 * @Apidoc\Sort("250")
 */
class Goods extends BaseController
{
    /**
    * @Apidoc\Title("商品管理列表")
    * @Apidoc\Query(ref="pagingQuery")
    * @Apidoc\Query(ref="sortQuery")
    * @Apidoc\Query(ref="searchQuery")
    * @Apidoc\Query(ref="dateQuery")
    * @Apidoc\Returned(ref="expsReturn")
    * @Apidoc\Returned(ref="pagingReturn")
    * @Apidoc\Returned("list", type="array", desc="商品管理列表", children={
    *   @Apidoc\Returned(ref="app\common\model\ShopProductModel", field="id,title,content,is_disable,create_time,update_time,store_platform_id,merchant_id,merchant_shop_id,setting_refund_id,shop_product_type_id,status,money,remark,b_is_delivery,b_delivery_price,b_coupon_url,b_coupon_price,c_sort_type,c_pay_num,c_start_price,c_end_price,c_region_id,c_order_remark,c_subject,d_enter_type,e_revoke_time,f_auth_type,f_reward_price,h_pay_time,h_pay_type,sort,order_num,f_increment_num,f_increment_price,d_comment_num,d_comment_price,b_product_num,b_product_price")
    * })
    */
    public function list()
    {
        $param = $this->params([
            'cid/d'=>0,//分类
            'back/d'=>10,//每页条数
            'min_id/d'=>1,//第几页
            'nav/d'=>3,//默认是全部商品
            'sale_type/d'=>2,//榜单类型：2.今日爆单榜
        ]);
        $queryString = http_build_query($param);
        $http = new Http('goodsItem');
        $setting = SettingService::info('tblm_goods_bd_url,tblm_is_open,tblm_api_key,tblm_service_price,tblm_subsidy_ratio,tblm_subsidy_price');
        //检测淘宝联盟是否开启
        if($setting['tblm_is_open']!=1){
            $data['list'] =[];
            $data['min_id'] =1;
        }else{
            $api_res  = $http->get($setting['tblm_goods_bd_url']."?apikey=".$setting['tblm_api_key']."&".$queryString);
            $data['list'] = isset($api_res['data'])?$api_res['data']:[];
            foreach ($data['list'] as $key=>$val){
                $data['list'][$key]['subsidy']= 0;
                if (isset($val['tkrates'])){
                    $subsidy =$val['tkmoney'];
                    //平台服务费
                    if($setting['tblm_service_price']>0 && $subsidy>0){
                        $tblm_service_price = bcdiv(($subsidy*$setting['tblm_service_price']),100,2);
                        $subsidy =bcsub($subsidy,$tblm_service_price,2);
                    }
                    //用户补贴
                    if($setting['tblm_subsidy_ratio']>0 && $subsidy>0){
                        $subsidy =bcdiv(($subsidy*$setting['tblm_subsidy_ratio']),100,2);
                    }
                    //额外补贴
                    if($setting['tblm_subsidy_price']>0){
                        $subsidy =bcadd($subsidy, $setting['tblm_subsidy_price'],2);
                    }
                    $data['list'][$key]['subsidy']=$subsidy;
                }
            }
            $data['min_id'] = isset($api_res['min_id'])?$api_res['min_id']:($param['min_id']+1);
        }
        return success($data);
    }
    /**
     * @Apidoc\Title("商品详情")
     * @Apidoc\Query(ref="pagingQuery")
     * @Apidoc\Query(ref="sortQuery")
     * @Apidoc\Query(ref="searchQuery")
     * @Apidoc\Query(ref="dateQuery")
     * @Apidoc\Returned(ref="expsReturn")
     * @Apidoc\Returned(ref="pagingReturn")
     * @Apidoc\Returned("list", type="array", desc="商品管理列表", children={
     *   @Apidoc\Returned(ref="app\common\model\ShopProductModel", field="id,title,content,is_disable,create_time,update_time,store_platform_id,merchant_id,merchant_shop_id,setting_refund_id,shop_product_type_id,status,money,remark,b_is_delivery,b_delivery_price,b_coupon_url,b_coupon_price,c_sort_type,c_pay_num,c_start_price,c_end_price,c_region_id,c_order_remark,c_subject,d_enter_type,e_revoke_time,f_auth_type,f_reward_price,h_pay_time,h_pay_type,sort,order_num,f_increment_num,f_increment_price,d_comment_num,d_comment_price,b_product_num,b_product_price")
     * })
     */
    public function info()
    {
        $param = $this->params([
            'itemid/s' => 0,//商品id
        ]);
        validate(GoodsValidate::class)->scene('info')->check($param);
        $queryString = http_build_query($param);
        $http = new Http('goodsItem');
        $setting = SettingService::info('tblm_goods_info_url,tblm_api_key,tblm_service_price,tblm_subsidy_ratio,tblm_subsidy_price');
        $api_res = $http->get($setting['tblm_goods_info_url'] . "?apikey=" . $setting['tblm_api_key'] . "&" . $queryString);
        $data = isset($api_res['data']) ? $api_res['data'] : [];
        //商品分享标题处理
        $data['share_title'] = "";
        if(isset($data['itemendprice'])){
            $data['share_title'] .="【￥".$data['itemendprice']."元";
        }

        if (isset($data['tkrates'])){
            $subsidy =$data['tkmoney'];
            //平台服务费
            if($setting['tblm_service_price']>0 && $subsidy>0){
                $tblm_service_price = bcdiv(($subsidy*$setting['tblm_service_price']),100,2);
                $subsidy =bcsub($subsidy,$tblm_service_price,2);
            }
            //用户补贴
            if($setting['tblm_subsidy_ratio']>0 && $subsidy>0){
                $subsidy =bcdiv(($subsidy*$setting['tblm_subsidy_ratio']),100,2);
            }
            //额外补贴
            if($setting['tblm_subsidy_price']>0){
                $subsidy =bcadd($subsidy, $setting['tblm_subsidy_price'],2);
            }
            $data['subsidy']=$subsidy;
            if($data['share_title']!=""){
                $data['share_title'] .=",平台补贴".$subsidy."元";
            }else{
                $data['share_title'] .="【平台补贴".$subsidy."元";
            }
        }
        //轮播图
        if (isset($data['taobao_image'])){
            $data['taobao_image'] = explode(',',$data['taobao_image']);
        }
        //活动结束时间
        if(isset($data['end_time'])){
            // 获取当前时间的时间戳
            $current_time = new DateTime();
            $current_timestamp = $current_time->getTimestamp();
            $data['time_diff_in_seconds'] =$data['end_time'] - $current_timestamp;
        }
        if($data['share_title']!=""){
            $data['share_title'] .="】";
        }
        $data['share_title'] .= isset($data['itemshorttitle'])?$data['itemshorttitle']:'';
        return success($data);
    }
    /**
     * @Apidoc\Title("淘宝商品转链")
     * @Apidoc\Query(ref="pagingQuery")
     * @Apidoc\Query(ref="sortQuery")
     * @Apidoc\Query(ref="searchQuery")
     * @Apidoc\Query(ref="dateQuery")
     * @Apidoc\Returned(ref="expsReturn")
     * @Apidoc\Returned(ref="pagingReturn")
     * @Apidoc\Returned("list", type="array", desc="商品管理列表", children={
     *   @Apidoc\Returned(ref="app\common\model\ShopProductModel", field="id,title,content,is_disable,create_time,update_time,store_platform_id,merchant_id,merchant_shop_id,setting_refund_id,shop_product_type_id,status,money,remark,b_is_delivery,b_delivery_price,b_coupon_url,b_coupon_price,c_sort_type,c_pay_num,c_start_price,c_end_price,c_region_id,c_order_remark,c_subject,d_enter_type,e_revoke_time,f_auth_type,f_reward_price,h_pay_time,h_pay_type,sort,order_num,f_increment_num,f_increment_price,d_comment_num,d_comment_price,b_product_num,b_product_price")
     * })
     */
    public function ratesUrl()
    {
        $param = $this->params([
            'itemid/s' => 0,//商品id
            'title/s'=>'',
        ]);
        validate(GoodsValidate::class)->scene('info')->check($param);
        $queryString = http_build_query($param);
        $http = new Http('goodsItem');

        $setting = SettingService::info('tblm_rates_url,tblm_api_key,tblm_api_pid,tblm_auth_name,tblm_service_price,tblm_subsidy_ratio,tblm_subsidy_price');

        $body = [
            "apikey"=>$setting['tblm_api_key'],
            "pid"=>$setting['tblm_api_pid'],
            "tb_name"=>$setting['tblm_auth_name'],
            "itemid"=>$param['itemid'],
            "title"=>$param['title'],
            "get_taoword"=>1
        ];
        $headers = [];

        $api_res  = $http->post($setting['tblm_rates_url'],$body,$headers);
        $data = isset($api_res['data']) ? $api_res['data'] : [];
        $data['taobo_click_url'] = "taobao://".preg_replace("/^https?:\/\//", "", $data['coupon_click_url']);
        return success($data);
    }
    /**
     * @Apidoc\Title("淘宝商品搜索")
     * @Apidoc\Query(ref="pagingQuery")
     * @Apidoc\Query(ref="sortQuery")
     * @Apidoc\Query(ref="searchQuery")
     * @Apidoc\Query(ref="dateQuery")
     * @Apidoc\Returned(ref="expsReturn")
     * @Apidoc\Returned(ref="pagingReturn")
     * @Apidoc\Returned("list", type="array", desc="淘宝商品搜索", children={
     *   @Apidoc\Returned(ref="app\common\model\ShopProductModel", field="id,title,content,is_disable,create_time,update_time,store_platform_id,merchant_id,merchant_shop_id,setting_refund_id,shop_product_type_id,status,money,remark,b_is_delivery,b_delivery_price,b_coupon_url,b_coupon_price,c_sort_type,c_pay_num,c_start_price,c_end_price,c_region_id,c_order_remark,c_subject,d_enter_type,e_revoke_time,f_auth_type,f_reward_price,h_pay_time,h_pay_type,sort,order_num,f_increment_num,f_increment_price,d_comment_num,d_comment_price,b_product_num,b_product_price")
     * })
     */
    public function getGoodsSearch()
    {
        $param = $this->params([
            'cid/d'=>0,//分类
            'back/d'=>10,//每页条数
            'min_id/d'=>1,//第几页
            'tb_p/d'=>1,//淘宝分页
            'nav/d'=>3,//默认是全部商品
            'keyword/s'=>null
        ]);
        $sort =$this->params([
            'sort_field/s'=>null,
            'sort_value/s'=>null,
            'keyword/s'=>null
        ]);
        $param['sort']= $this->sort($sort['sort_field'],$sort['sort_value'],$sort['keyword']);
        $http = new Http('goodsItem');
        $setting = SettingService::info('tblm_is_open,tblm_goods_list_url,tblm_goods_search_url,tblm_api_key,tblm_service_price,tblm_subsidy_ratio,tblm_subsidy_price');
        //检测淘宝联盟是否开启
        if($setting['tblm_is_open']!=1){
            $data['list'] =[];
            $data['min_id'] =1;
        }else {
            /*********************************域名及参数处理********************************/
            $url = $param['keyword'] ? $setting['tblm_goods_search_url'] : $setting['tblm_goods_list_url'];
            $url .= "?apikey=" . $setting['tblm_api_key'];
            if ($param['keyword']) {
                $url .= "&keyword=" . urlencode($param['keyword']) . "&back=" . $param['back'] . "&min_id=" . $param['min_id'] . "&tb_p=" . $param['tb_p'] . "&sort=" . $param['sort'];
            } else {
                $url .= "&cid=" . $param['cid'] . "&nav=" . $param['nav'] . "&back=" . $param['back'] . "&min_id=" . $param['min_id'] . "&sort=" . $param['sort'];
            }
            $api_res = $http->get($url);
            $data['list'] = isset($api_res['data']) ? $api_res['data'] : [];
            foreach ($data['list'] as $key => $val) {
                $data['list'][$key]['subsidy'] = 0;
                if (isset($val['tkrates'])) {
                    $subsidy = $val['tkmoney'];
                    //平台服务费
                    if ($setting['tblm_service_price'] > 0 && $subsidy > 0) {
                        $tblm_service_price = bcdiv(($subsidy * $setting['tblm_service_price']), 100, 2);
                        $subsidy = bcsub($subsidy, $tblm_service_price, 2);
                    }
                    //用户补贴
                    if ($setting['tblm_subsidy_ratio'] > 0 && $subsidy > 0) {
                        $subsidy = bcdiv(($subsidy * $setting['tblm_subsidy_ratio']), 100, 2);
                    }
                    //额外补贴
                    if ($setting['tblm_subsidy_price'] > 0) {
                        $subsidy = bcadd($subsidy, $setting['tblm_subsidy_price'], 2);
                    }
                    $data['list'][$key]['subsidy'] = $subsidy;
                }
            }
            $data['min_id'] = isset($api_res['min_id']) ? $api_res['min_id'] : ($param['min_id'] + 1);
            $data['tb_p'] = isset($api_res['tb_p']) ? $api_res['tb_p'] : ($param['tb_p'] + 1);
        }
        return success($data);
    }

    //排序处理
    private function sort($sort_field,$sort_value,$keyword)
    {
        $sort =0;
        if($sort_field && $sort_value){
            switch ($sort_field){
                case 'goods_show_price'://价格
                    if($keyword){//查询接口
                        if($sort_value=='desc'){
                            $sort = 5;
                        }else{
                            $sort = 4;
                        }
                    }else{//列表接口
                        if($sort_value=='desc'){
                            $sort = 2;
                        }else{
                            $sort = 1;
                        }
                    }
                    break;
                case 'order_sales'://销量
                    if($keyword){//查询接口
                        if($sort_value=='asc'){
                            $sort = 3;
                        }else{
                            $sort = 2;
                        }
                    }else{//列表接口
                        if($sort_value=='asc'){
                            $sort = 7;
                        }else{
                            $sort = 4;
                        }
                    }
                    break;
                case 'commission'://佣金
                    if($keyword){//查询接口
                        $sort = 6;
                    }else{//列表接口
                        if($sort_value=='asc'){
                            $sort = 8;
                        }else{
                            $sort = 5;
                        }
                    }
                    break;
            }
        }
        return $sort;
    }
    /**
     * @Apidoc\Title("订单号提交验证")
     * @Apidoc\Query(ref="pagingQuery")
     * @Apidoc\Query(ref="sortQuery")
     * @Apidoc\Query(ref="searchQuery")
     * @Apidoc\Query(ref="dateQuery")
     * @Apidoc\Returned(ref="expsReturn")
     * @Apidoc\Returned(ref="pagingReturn")
     * @Apidoc\Returned("list", type="array", desc="订单号提交验证", children={
     *   @Apidoc\Returned(ref="app\common\model\ShopProductModel", field="id,title,content,is_disable,create_time,update_time,store_platform_id,merchant_id,merchant_shop_id,setting_refund_id,shop_product_type_id,status,money,remark,b_is_delivery,b_delivery_price,b_coupon_url,b_coupon_price,c_sort_type,c_pay_num,c_start_price,c_end_price,c_region_id,c_order_remark,c_subject,d_enter_type,e_revoke_time,f_auth_type,f_reward_price,h_pay_time,h_pay_type,sort,order_num,f_increment_num,f_increment_price,d_comment_num,d_comment_price,b_product_num,b_product_price")
     * })
     */
    public function submitOrder()
    {
        $param = $this->params(['order_on/s'=>'']);
        validate(GoodsValidate::class)->scene('submitOrder')->check($param);
        $member_id = member_id(true);
        $data =self::getTblm($param['order_on'],$member_id);
        return success($data);
    }
    private function getTblm($order_on,$member_id)
    {
        //查询是否已有订单
        $tblm_order = TblmOrderService::getInfo($order_on,false);
        if(count($tblm_order)>0){
            if($tblm_order['member_id'] !=$member_id){
                exception('您的返利订单已被他人领取，请联系平台客服');
            }
            return $tblm_order;
        }
        $http = new Http('submitOrder');
        $setting = SettingService::info('tblm_order_url,tblm_api_key,tblm_appid,tblm_app_secret,tblm_service_price,tblm_subsidy_ratio,tblm_subsidy_price');
        $date = date('Y-m-d H:i:s');
        $body = [
            "method"=>"query.order",
            "app_id"=>$setting['tblm_appid'],
            "date"=>$date,
            "tradeid"=>$order_on,
            "get_orders"=>0,//是否获取全部子订单（0.否；1.是）注：获取子订单结构将会改变
        ];
        /*********************************************签名********************************************/
        ksort($body);
        $stringToBeSigned = '';
        foreach($body as $k => $v)
        {
            $stringToBeSigned .= "$k$v";
        }
        $body['sign'] = strtoupper(md5($stringToBeSigned.$setting['tblm_app_secret']));
        $headers = [];
        $api_res  = $http->post($setting['tblm_order_url'],$body,$headers);
        $data =[];
        if(isset($api_res['data']) && count($api_res['data'])>0){
            $add_data =$api_res['data'];
            $data=$api_res['data'];
            $add_data['member_id'] = $member_id;
            //结算金额计算
            $subsidy =isset($data['pub_share_fee'])?$data['pub_share_fee']:0;
            //平台服务费
            if($setting['tblm_service_price']>0 && $subsidy>0){
                $tblm_service_price = bcdiv(($subsidy*$setting['tblm_service_price']),100,2);
                $subsidy =bcsub($subsidy,$tblm_service_price,2);
            }
            //用户补贴
            if($setting['tblm_subsidy_ratio']>0 && $subsidy>0){
                $subsidy =bcdiv(($subsidy*$setting['tblm_subsidy_ratio']),100,2);
            }
            //额外补贴
            if($setting['tblm_subsidy_price']>0){
                $subsidy =bcadd($subsidy, $setting['tblm_subsidy_price'],2);
            }
            $add_data['settlement_price'] =$subsidy;
            //查看订单是否已失效
            if(isset($add_data['tk_status']) && $add_data['tk_status']==13){
                $add_data['status']=3;
            }
            $add_res = TblmOrderService::add($add_data);
        }
        return $data;
    }
    /**
     * @Apidoc\Title("查询联盟订单列表")
     * @Apidoc\Query(ref="pagingQuery")
     * @Apidoc\Query(ref="sortQuery")
     * @Apidoc\Query(ref="searchQuery")
     * @Apidoc\Query(ref="dateQuery")
     * @Apidoc\Returned(ref="expsReturn")
     * @Apidoc\Returned(ref="pagingReturn")
     * @Apidoc\Returned("list", type="array", desc="查询联盟订单列表", children={
     *   @Apidoc\Returned(ref="app\common\model\ShopProductModel", field="id,title,content,is_disable,create_time,update_time,store_platform_id,merchant_id,merchant_shop_id,setting_refund_id,shop_product_type_id,status,money,remark,b_is_delivery,b_delivery_price,b_coupon_url,b_coupon_price,c_sort_type,c_pay_num,c_start_price,c_end_price,c_region_id,c_order_remark,c_subject,d_enter_type,e_revoke_time,f_auth_type,f_reward_price,h_pay_time,h_pay_type,sort,order_num,f_increment_num,f_increment_price,d_comment_num,d_comment_price,b_product_num,b_product_price")
     * })
     */
    public function getGoodsOrderList()
    {
        $where = $this->where(where_delete());
        $member_id = member_id(true);
        $where[] = ['member_id','=',$member_id];
        $param = $this->params(['trade_id/s'=>'']);
        if($param['trade_id']){
            $where[] = ['trade_id','like',"%".$param['trade_id']."%"];
            //查询是否已有订单
            $order_count = TblmOrderService::getCountByWhere($where);
            if($order_count<=0){
                $data =self::getTblm($param['trade_id'],$member_id);
                if(count($data)<=0){
                    exception('未查询到该订单，请稍后再试');
                }
            }
        }
        $data = TblmOrderService::list($where, $this->page(), $this->limit(), $this->order());
        return success($data);
    }
    /**
     * @Apidoc\Title("商品海报生成")
     * @Apidoc\Query(ref="pagingQuery")
     * @Apidoc\Query(ref="sortQuery")
     * @Apidoc\Query(ref="searchQuery")
     * @Apidoc\Query(ref="dateQuery")
     * @Apidoc\Returned(ref="expsReturn")
     * @Apidoc\Returned(ref="pagingReturn")
     * @Apidoc\Returned("list", type="array", desc="商品海报生成", children={
     *   @Apidoc\Returned(ref="app\common\model\ShopProductModel", field="id,title,content,is_disable,create_time,update_time,store_platform_id,merchant_id,merchant_shop_id,setting_refund_id,shop_product_type_id,status,money,remark,b_is_delivery,b_delivery_price,b_coupon_url,b_coupon_price,c_sort_type,c_pay_num,c_start_price,c_end_price,c_region_id,c_order_remark,c_subject,d_enter_type,e_revoke_time,f_auth_type,f_reward_price,h_pay_time,h_pay_type,sort,order_num,f_increment_num,f_increment_price,d_comment_num,d_comment_price,b_product_num,b_product_price")
     * })
     */
    public function createPoster()
    {
        $param = $this->params([
            'title/s'=>'',
            'image/s'=>'',
            'price/f'=>0,
            'original_price/f'=>0,
            'platform/s'=>'wechat',//wechat:微信小程序、routine：其它
            'goods_type/d'=>1,//1、淘宝联盟 2、优惠补贴商品
            'field_name/s'=>"",//商品详情页id名称
            'field_value/s'=>"",//商品详情页id
        ]);
        $data = ShopProductService::createPoster($param);
        return success($data);
    }
}
